import com.sun.source.tree.Tree;

import java.util.*;

public class Solution {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    }   `

    //之字形打印二叉树
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        // write code here
        ArrayList<ArrayList<Integer>> ret = new ArrayList<>();

        if(pRoot == null){
            return ret;
        }

        //利用queue进行层序遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        boolean flag = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            if(flag){
                flag = false;
            }else {
                Collections.reverse(list);
                flag = true;
            }
            ret.add(list);
        }
        return ret;
    }
}
